package com.xincheng.shuimalong.activity.recept;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.SwitchCompat;
import android.text.Editable;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.xincheng.library.drawable.Location;
import com.xincheng.library.util.CommonUtil;
import com.xincheng.library.util.DateUtil;
import com.xincheng.library.util.PrefUtil;
import com.xincheng.library.util.UIUtil;
import com.xincheng.library.widget.pickerview.OptionsPickerView;
import com.xincheng.library.widget.pickerview.TimePickerView;
import com.xincheng.library.xlog.XLog;
import com.xincheng.shuimalong.R;
import com.xincheng.shuimalong.activity.BaseActivity;
import com.xincheng.shuimalong.activity.config.CitySelectActivity;
import com.xincheng.shuimalong.activity.config.InsuranceCompanyActivity;
import com.xincheng.shuimalong.api.AppUrl;
import com.xincheng.shuimalong.api.BaseObserver;
import com.xincheng.shuimalong.api.PostParam;
import com.xincheng.shuimalong.api.RetroSubscrube;
import com.xincheng.shuimalong.common.IntentKey;
import com.xincheng.shuimalong.common.PrefKey;
import com.xincheng.shuimalong.common.RequestCodeKey;
import com.xincheng.shuimalong.entity.config.CommonConfig;
import com.xincheng.shuimalong.entity.config.District;
import com.xincheng.shuimalong.entity.config.RegionData;
import com.xincheng.shuimalong.entity.recept.Acceptance;
import com.xincheng.shuimalong.util.CalenderUtil;
import com.xincheng.shuimalong.util.ConfigUtil;
import com.xincheng.shuimalong.util.MyUtil;
import com.xincheng.shuimalong.util.ShowActivity;
import com.xincheng.shuimalong.view.QuantityView;
import com.xincheng.shuimalong.view.picker.AreaPickerView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import butterknife.OnTextChanged;

/**
 * Created by xiaote on 2017/6/20.
 * 填写发布信息
 */

public class FillReceiptInfoActivity extends BaseActivity {
    @BindView(R.id.fill_info_rg)
    RadioGroup mFillInfoRg;
    @BindView(R.id.fill_info_new_old_car_switch)
    SwitchCompat mNewOldCarSwitch;
    @BindView(R.id.fill_info_usage_rg)
    RadioGroup mUsageRg;
    @BindView(R.id.fill_info_vcirb_qv)
    QuantityView mVcirbQv;
    @BindView(R.id.fill_info_tcirb_qv)
    QuantityView mTcirbQv;
    @BindView(R.id.fill_info_car_load_title_tv)
    TextView mCarLoadTitleTv;
    @BindView(R.id.fill_info_car_load_tv)
    TextView mCarLoadTv;
    @BindView(R.id.fill_info_insurance_city_tv)
    TextView mInsuranceCityTv;
    @BindView(R.id.fill_info_insurance_company_tv)
    TextView mInsuranceCompanyTv;
    @BindView(R.id.fill_info_putin_date_title_tv)
    TextView mPutinDateTitleTv;
    @BindView(R.id.fill_info_putin_date_tv)
    TextView mPutinDateTv;
    @BindView(R.id.fill_info_finish_date_tv)
    TextView mFinshDateTv;
    @BindView(R.id.fill_info_leave_et)
    EditText mLeaveEt;
    @BindView(R.id.fill_info_leave_length_tv)
    TextView mLeaveLengthTv;

    private String mToken = "";
    private int mCarType = 1;
    private int mVciRb = 0;
    private int mTciRb = 0;
    private int mNewCar = 2;
    private int mCarWeight = 0;
    private int mCity = 0;
    private int mInsuranceCompany = 0;
    private String mStartDate = "";
    private String mEndDate = "";
    private String mBak = "";
    private int mLongTerm = 0;
    private int mUsage = 2;

    private List<CommonConfig> mNewCarTypes;
    private List<CommonConfig> mTruckWeightTypes;
    private AreaPickerView mAreaPickerView;
    private OptionsPickerView<CommonConfig> mTruckWeightTypePickerView;
    private TimePickerView mPutDatePickerView, mEndDatePickerView;
    private long mStartDateTime, mEndDateTime;
    private CommonConfig mCompany;

    @Override
    public int getLayoutResId() {
        return R.layout.activity_fill_information;
    }

    private void initConfigData() {
        mNewCarTypes = ConfigUtil.getCommonConfigList(this, PrefKey.NEW_CAR_TYPE);
        mTruckWeightTypes = ConfigUtil.getCommonConfigList(this, PrefKey.TRUCK_WEIGHT_TYPES);
    }

    private void initOptionsPicker() {
        mTruckWeightTypePickerView = new OptionsPickerView.Builder(this, new OptionsPickerView
                .OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                CommonConfig truckWeight = mTruckWeightTypes.get(options1);
                mCarLoadTv.setText(truckWeight.getPickerViewText());
                mCarWeight = truckWeight.getId();
            }
        }).setTitleText(getString(R.string.fill_truck_loading)).build();
        mTruckWeightTypePickerView.setPicker(mTruckWeightTypes);
    }

    private void initPickerView() {
        List<RegionData> provinceList = ConfigUtil.getRegionDataList(this, PrefKey.PROVINCE_LIST);
        mAreaPickerView = new AreaPickerView.Builder(this, new AreaPickerView.OnAreaSelectListener() {
            @Override
            public void onAreaSelect(RegionData province, RegionData city, District district, View v) {
                mInsuranceCityTv.setText(province.getName() + city.getName());
                mCity = city.getId();
            }
        }).showDistrict(false).setTitleText(getString(R.string.area_select)).build();
        mAreaPickerView.setPicker(provinceList);
    }

    private void initTimePicker() {
        Calendar selectedDate = Calendar.getInstance();
        mStartDateTime = selectedDate.getTimeInMillis();
        mEndDateTime = selectedDate.getTimeInMillis();
        mPutDatePickerView = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                mStartDateTime = date.getTime();
                mStartDate = DateUtil.parseDate(date);
                mPutinDateTv.setText(DateUtil.getDate(date));
            }
        })
                .setDate(selectedDate)
                .isCyclic(true)
                .setRangDate(CalenderUtil.getRangeStartDate(), CalenderUtil.getRangeEndDate())
                .setTitleText(getString(R.string.putin_date))
                .setType(new boolean[]{true, true, true, false, false, false})
                .isCenterLabel(false)
                .build();
        mEndDatePickerView = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                mEndDateTime = date.getTime();
                mEndDatePickerView.setCanDismiss(true);
                if (mEndDateTime < mStartDateTime) {
                    mEndDatePickerView.setCanDismiss(false);
                    showToast("结束时间不能小于投放时间");
                    return;
                }
                mEndDate = DateUtil.parseDate(date);
                mFinshDateTv.setText(DateUtil.getDate(date));
            }
        })
                .setDate(selectedDate)
                .isCyclic(true)
                .setRangDate(CalenderUtil.getRangeStartDate(), CalenderUtil.getRangeEndDate())
                .setTitleText(getString(R.string.finish_date))
                .setType(new boolean[]{true, true, true, false, false, false})
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .build();
    }

    private void initPicker() {
        initOptionsPicker();
        initTimePicker();
        initPickerView();
    }

    @OnTextChanged(value = R.id.fill_info_leave_et, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    public void afterTextChanged(Editable s) {
        mLeaveLengthTv.setText(String.valueOf(getResources().getInteger(R.integer.edit_length_default_200)
                - s.length()));
    }

    @Override
    public void initData() {
        initTitleBar(getString(R.string.fill_information));
        initConfigData();
        initPicker();
        mToken = PrefUtil.getString(this, PrefKey.TOKEN, "");
        mPutinDateTitleTv.setText(getString(R.string.putin_date));
        mNewCar = mNewCarTypes.get(1).getId();
        initCarLoad(mCarType);
    }

    private void initCarLoad(int carType) {
        switch (carType) {
            case 1:
                mCarLoadTitleTv.setText(getString(R.string.fill_saloon_loading));
                mCarLoadTv.setText(getString(R.string.seat_nums));
                UIUtil.setDrawable(this, mCarLoadTv, R.drawable.icon_right_arrow, Location.NONE);
                mCarLoadTv.setTextColor(ContextCompat.getColor(this, R.color.black_66));
                break;
            case 2:
                mCarWeight = mTruckWeightTypes.get(0).getId();
                mCarLoadTv.setText(mTruckWeightTypes.get(0).getName());
                mCarLoadTitleTv.setText(R.string.fill_truck_loading);
                UIUtil.setDrawable(this, mCarLoadTv, R.drawable.icon_right_arrow, Location.RIGHT);
                mCarLoadTv.setTextColor(ContextCompat.getColor(this, R.color.blue1));
                break;
        }
    }

    @OnClick({R.id.fill_info_car_load_tv, R.id.fill_info_insurance_city_tv,
            R.id.fill_info_insurance_company_tv, R.id.fill_info_putin_date_tv,
            R.id.fill_info_finish_date_tv, R.id.fill_info_submit_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.fill_info_car_load_tv://轿车(承载人数) 货车(重量)
                XLog.d("carType->" + mCarType);
                switch (mCarType) {
                    case 1:
                        mCarLoadTv.setText(getString(R.string.seat_nums));
                        break;
                    case 2:
                        if (mTruckWeightTypePickerView != null) {
                            mTruckWeightTypePickerView.show();
                        }
                        break;
                }
                break;
            case R.id.fill_info_insurance_city_tv://城市选择
                mAreaPickerView.show();
                break;
            case R.id.fill_info_insurance_company_tv://保险公司选择
                Bundle extras = new Bundle();
                if (mCompany != null) {
                    extras.putParcelable(IntentKey.INSURANCE_COMPANY, mCompany);
                }
                ShowActivity.showActivityForResult(this, InsuranceCompanyActivity.class, extras,
                        RequestCodeKey.GO_INSURANCE_COMPAY_SELECT);
                break;
            case R.id.fill_info_putin_date_tv:  //投放时间
                if (mPutDatePickerView != null) {
                    mPutDatePickerView.show();
                }
                break;
            case R.id.fill_info_finish_date_tv://结束时间
                if (mEndDatePickerView != null) {
                    mEndDatePickerView.show();
                }
                break;
            case R.id.fill_info_submit_btn://提交
                if (checkData()) {
                    mBak = mLeaveEt.getText().toString().trim();
                    mVciRb = mVcirbQv.getQuantity();
                    mTciRb = mTcirbQv.getQuantity();
                    publishAcceptance();
                }
                break;
        }
    }

    private boolean checkData() {
        if (CommonUtil.isEmpty(mInsuranceCityTv)) {
            CommonUtil.showToast(this, "城市不能为空");
            return false;
        }
        if (CommonUtil.isEmpty(mInsuranceCompanyTv)) {
            CommonUtil.showToast(this, "保险公司不能为空");
            return false;
        }
        if (mVcirbQv.isNullText()) {
            CommonUtil.showToast(this, "商业险酬金不能为空");
            return false;
        }
        if (mTcirbQv.isNullText()) {
            CommonUtil.showToast(this, "交强险酬金不能为空");
            return false;
        }
        return true;
    }

    private void publishAcceptance() {
        RetroSubscrube.getInstance().postSubscrube(AppUrl.PUBLISH_ACCEPTANCE, PostParam.publishAcceptance(mToken,
                mCity, mInsuranceCompany, mCarType, mNewCar, mUsage, mTciRb, mVciRb, mStartDate, mEndDate, mCarWeight,
                mBak, mLongTerm), new BaseObserver(this, getString(R.string.loading_submit)) {
            @Override
            protected void onHandleSuccess(Object data, String msg) {
                CommonUtil.showToast(getContext(), msg);
                Intent intent = new Intent();
                intent.putExtra(IntentKey.SUCCESS, true);
                setResult(RESULT_OK, intent);
                finish();
            }
        });
    }

    @OnCheckedChanged(R.id.fill_info_new_old_car_switch)
    public void onButtonChecked(CompoundButton button, boolean isChecked) {
        if (isChecked) {
            mNewCar = mNewCarTypes.get(0).getId();
        } else {
            mNewCar = mNewCarTypes.get(1).getId();
        }
    }

    @Override
    public void addListener() {
        MyOnCheckedChangedListener listener = new MyOnCheckedChangedListener();
        mFillInfoRg.setOnCheckedChangeListener(listener);
        mUsageRg.setOnCheckedChangeListener(listener);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RequestCodeKey.GO_CITY_SELECT://城市选择回调
//                    CommonConfig hotCity = data.getParcelableExtra(IntentKey.HOT_CITY);
//                    if (hotCity != null) {
//                        mInsuranceCityTv.setText(hotCity.getName());
//                        mCity = hotCity.getId();
//                    } else  {
//                        RegionData province = data.getParcelableExtra(IntentKey.PROVINCE);
//                        RegionData city = data.getParcelableExtra(IntentKey.CITY);
//                        String name = "";
//                        if (province != null) {
//                            name += province.getName();
//                        }
//                        if (city != null) {
//                            mCity = city.getId();
//                            name += city.getName();
//                        }
//                        mInsuranceCityTv.setText(name);
//                    }
                    break;
                case RequestCodeKey.GO_INSURANCE_COMPAY_SELECT://保险公司选择回调
                    mCompany = data.getParcelableExtra(IntentKey.INSURANCE_COMPANY);
                    if (mCompany != null) {
                        mInsuranceCompany = mCompany.getId();
                        mInsuranceCompanyTv.setText(mCompany.getName());
                    }
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private class MyOnCheckedChangedListener implements RadioGroup.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(RadioGroup radioGroup, @IdRes int checkId) {
            switch (radioGroup.getId()) {
                case R.id.fill_info_rg:
                    switch (checkId) {
                        case R.id.fill_info_car_rb:
                            mCarType = 1;
                            initCarLoad(1);
                            releaseData();
                            break;
                        case R.id.fill_info_truck_rb:
                            mCarType = 2;
                            initCarLoad(2);
                            releaseData();
                            break;
                    }
                    break;
                case R.id.fill_info_usage_rg:
                    switch (checkId) {
                        case R.id.fill_info_operation_rb:
                            mUsage = 1;
                            break;
                        case R.id.fill_info_operation_not_rb:
                            mUsage = 2;
                            break;
                    }
                    break;
            }
        }
    }


    private void releaseData() {
        mNewCar = mNewCarTypes.get(1).getId();
        mVciRb = 0;
        mTciRb = 0;
        mCarWeight = 0;
        mInsuranceCompany = 0;
        mCity = 0;
        mCarWeight = 0;
        mLongTerm = 0;
        mStartDate = "";
        mEndDate = "";
        mBak = "";
        mNewOldCarSwitch.setChecked(false);
        mUsage = 2;
        mUsageRg.check(R.id.fill_info_operation_not_rb);
        mInsuranceCityTv.setText("");
        mInsuranceCompanyTv.setText("");
        mPutinDateTv.setText("");
        mFinshDateTv.setText("");
    }
}
